// 引入
const Koa = require("koa"); // 创建服务端应用的
const KoaRouter = require("koa-router"); // 定义接口
const KoaBodyparser = require("koa-bodyparser"); // 解析请求体的

const mysql = require("mysql");

// 实例化
const app = new Koa();
const router = new KoaRouter();

// 请求处理函数
router.post("/users", async (ctx) => {
    // 解析请求体
    const {
        username,
        email,
        mobile,
        create_time = new Date(),
    } = ctx.request.body;
    const res = await send(
        "insert into user (name, email, mobile, create_time) values (?, ?, ?, ?);",
        [username, email, mobile, create_time]
    );
    ctx.body = res;
});

router.get("/users", async (ctx) => {
    const data = await send("select * from user");
    // 设置 ctx.body
    ctx.body = data;
});

app.use(KoaBodyparser());
app.use(router.routes());

// 监听端口，提供服务
app.listen(9000, () => {
    console.log("http://localhost:9000");
});

function send(sql, params = []) {
    // 建立链接
    const con = mysql.createConnection({
        // TCP 链接的配置
        host: "localhost",
        port: 3306,
        // Mysql 服务器的配置
        user: "root",
        password: "root",
        database: "user",
    });

    // 发送 SQL 语句
    return new Promise((resolve, reject) => {
        con.query(sql, params, (error, data) => {
            if (error) {
                reject(error);
                return;
            }
            resolve(data);
        });

        // 关闭数据库链接
        con.end();
    });
}
